package com.lipuwater.agent.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blekit.BluetoothClient;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseActivity;
import com.lipuwater.agent.ble.DeviceNotice;
import com.lipuwater.agent.ble.DeviceWrite;
import com.lipuwater.agent.ble.command.DeviceCommand30;
import com.lipuwater.agent.ble.control.DeviceActivateControl;
import com.lipuwater.agent.ble.control.DeviceResetFilterControl;
import com.lipuwater.agent.ble.eventbus.DeviceBindingEvent;
import com.lipuwater.agent.ble.listener.NoticeListener;
import com.lipuwater.agent.ble.utils.ByteParsing;
import com.ismartlib.ui.widget.SlidingLinearLayout;
import com.ismartlib.utils.DisplayUtil;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import io.github.xudaojie.qrcodelib.CaptureActivity;
import mehdi.sakout.fancybuttons.FancyButton;



public class DeviceBindingActivity extends BaseActivity implements NoticeListener {

    @Bind(R.id.layout_stpe1)
    LinearLayout layoutStpe1;
    @Bind(R.id.layout_stpe2)
    LinearLayout layoutStpe2;
    @Bind(R.id.layout_stpe3)
    LinearLayout layoutStpe3;
    @Bind(R.id.layout_sliding)
    SlidingLinearLayout layoutSliding;
    @Bind(R.id.image_stpe)
    ImageView imageStpe;
    @Bind(R.id.edit_code)
    EditText editCode;
    @Bind(R.id.btn_stpe3)
    FancyButton btnStpe3;
    @Bind(R.id.btn_rinse)
    FancyButton btnRinse;


    private final int REQUEST_QR_CODE = 1;
    int mScreenWidth = 0;


    /**
     * 蓝牙操作对象
     */
    private DeviceWrite mDeviceWrite;
    private DeviceNotice mDeviceNotice;
    /**
     * 设备属性
     */
    private String mDeviceMac = "设备MAC地址";
    private String mDeviceName = "设备名称";
    private String mProductCode = "产品编码";

    private DeviceActivateControl mDeviceActivateControl;
    //定时器，轮询设备状态
    private Timer timer = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_binding);
        ButterKnife.bind(this);
        setStatusBar(R.id.view_status_bar);
        EventBus.getDefault().register(this);
        initView();
        mDeviceMac = getIntent().getStringExtra("DeviceMac"); //获取前一个页面的连接mac地址
        mDeviceName = getIntent().getStringExtra("deviceName");
        mDeviceNotice = new DeviceNotice();
        mDeviceNotice.Notify(mDeviceMac, this);
        mDeviceWrite = new DeviceWrite();
    }

    private void initView() {
        mScreenWidth = DisplayUtil.getScreenWidth(this);
        DisplayUtil.setViewWidth(layoutStpe1, mScreenWidth);
        DisplayUtil.setViewWidth(layoutStpe2, mScreenWidth);
        DisplayUtil.setViewWidth(layoutStpe3, mScreenWidth);
        btnStpe3.setClickable(false);
    }

    @Override
    public void BleNotice(byte[] value, int receiveMsg, boolean losePackage) {
        if (!losePackage) {//没丢包
            if (ByteParsing.getDeviceConfirmState(value)) {//如果已经按下
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                mDeviceNotice.unNotify();//取消监听通知和回调
                mDeviceActivateControl = new DeviceActivateControl(DeviceBindingActivity.this, token, mDeviceMac, mProductCode, mDeviceName, getIntent().getIntExtra("devId", 0), getIntent().getIntExtra("installType", 0));
               /* if (ByteParsing.getDeviceState(value)) {//已经激活
                    Toast("设备已经被激活");
                    btnStpe3.setBackgroundColor(ContextCompat.getColor(this, R.color.btn_color_blue_default));
                    btnStpe3.setClickable(true);
                    btnRinse.setVisibility(View.VISIBLE);
                } else {//未激活
                    mDeviceActivateControl = new DeviceActivateControl(DeviceBindingActivity.this, token, mDeviceMac, mProductCode, mDeviceName, getIntent().getIntExtra("devId", 0), getIntent().getIntExtra("installType", 0));
                }*/
            }
        }
    }

    /**
     * 激活绑定通知
     *
     * @param event
     */
    public void onEventMainThread(DeviceBindingEvent event) {
        if (event.getBinding()) {
            btnStpe3.setBackgroundColor(ContextCompat.getColor(this, R.color.btn_color_blue_default));
            btnStpe3.setClickable(true);
            btnRinse.setVisibility(View.VISIBLE);
        }
    }

    //定时查询设备按钮按下状态
    private void queryDeviceState() {
        if (timer != null) {
            return;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String[] address = new String[]{"12000", "12001"};
                        String data = DeviceCommand30.getCommand(address, "71");
                        mDeviceWrite.writeData(data, mDeviceMac, null);
                    }
                });
            }
        }, 100, 800);
    }

    @OnClick({R.id.layout_left, R.id.btn_stpe1, R.id.btn_stpe2, R.id.btn_stpe3, R.id.image_scan, R.id.btn_rinse})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_left:
                finish();
                break;
            case R.id.image_scan:
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.putExtra("flash", false);
                startActivityForResult(intent, REQUEST_QR_CODE);
                break;
            case R.id.btn_stpe1:
                layoutSliding.ScrollToX(0, mScreenWidth);
                imageStpe.setImageResource(R.drawable.img_ble_binding_step2);
                break;
            case R.id.btn_stpe2:
                if (editCode.getText().toString().equals("")) {
                    Toast("请输入或者扫描产品编码");
                    return;
                }
                mProductCode = editCode.getText().toString();
                layoutSliding.ScrollToX(layoutSliding.getCurrX(), mScreenWidth);
                imageStpe.setImageResource(R.drawable.img_ble_binding_step3);
                Toast("请按下设备确认按钮");
                queryDeviceState();
                break;
            case R.id.btn_stpe3:
                try {
                    MainActivity.mBleClient.disconnect(mDeviceMac);
                } catch (Exception e) {
                }
                finish();
                break;
            case R.id.btn_rinse:
                new DeviceResetFilterControl(DeviceBindingActivity.this, mDeviceMac, 0, true);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_QR_CODE && data != null) {
           try{
               String code = data.getStringExtra("result");
               if (code.indexOf("code=") != -1) {
                   code = code.substring(code.indexOf("code=") + 5, code.length());
               }
               editCode.setText(code);
           }catch (Exception e){}
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        BluetoothClient bleCliect = MainActivity.mBleClient;
        if (bleCliect != null) {
            bleCliect.disconnect(mDeviceMac);
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mDeviceNotice != null) {
            mDeviceNotice.unNotify();
        }
        if (mDeviceActivateControl != null) {
            mDeviceActivateControl.unRegister();
        }
        EventBus.getDefault().unregister(this);
    }


}
